package com.example.demo.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.example.demo.dao.*;
import com.example.demo.entry.*;
import com.example.demo.service.LedgerService;
import com.example.demo.service.OgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Component
public class Schedule {

    @Autowired
    private BlockDao blockService;

    @Autowired
    LedgerService ledgerService;

    @Autowired
    private OgService ogService;

    /**
     * 定时任务，每次执行之后5秒再次执行
     */
    @Scheduled(fixedDelay = 5000)
    public void DB_update() throws Exception {
        syn();
    }

    /**
     * 同步功能
     * 同步交易，块，地址进数据库
     */
    public void syn() throws Exception {
        Block b = blockService.findBlock();
        int fromHeight;
        if (b == null) {
            fromHeight = 0;
        } else {
            fromHeight = b.getHeight() + 1;
        }

        JSONObject jsonObject = JSONObject.parseObject(ogService.latestBlock(), Feature.OrderedField);
        JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
        //获取最新区块高度
        int toHeight = (Integer) data.get("Height");
        if (toHeight == fromHeight) return;

        // sync for each height
        for (int height = fromHeight; height <= toHeight; height++) {
            ledgerService.fullSync(height);
        }
    }

}
